<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input @clear="geteUserList" clearable v-model="queryInfo.query" placeholder="请输入内容">
            <el-button @click="geteUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 数据区域 -->
      <el-table :data="userlist" style="width: 100%" stripe border>
        <!--  data当前表格需要渲染的数据  -->
        <!--  stripe是否为斑马纹  -->
        <!--  border是否带有纵向边框  -->
        <el-table-column align="center" label="#" type="index" :index="indexMethod"></el-table-column>
        <el-table-column align="center" prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column align="center" prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column align="center" prop="mobile" label="电话"></el-table-column>
        <el-table-column align="center" prop="role_name" label="角色" width="180"></el-table-column>
        <!-- 使用作用域后,prop属性可以去掉,因为element在内部再次帮我们进行了处理 -->
        <!-- 内部将作用域插槽中使用的字段mg_state再次给prop进行了添加 -->
        <!-- <el-table-column align="center" prop="mg_state" label="状态"> -->
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <!-- scope.row 这个row属性是element底层给封装好的,主要作用:就是获取到当前这一行的数据 -->
            <el-switch v-model="scope.row.mg_state" @change="userStatueChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 增删改查 -->
        <el-table-column align="center" prop="address" label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              plain
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editUserHandle(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              @click="removeUserById(scope.row.id)"
              plain
              size="mini"
              type="danger"
              icon="el-icon-delete"
            ></el-button>
            <!-- 分配按钮 -->
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                @click="setRoles(scope.row)"
                plain
                size="mini"
                type="warning"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 12]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <!-- visible 控住弹框的显示和隐藏 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 弹框主体区域 -->
      <el-form :model="addForm" ref="addFormRef" label-width="70px" :rules="addFormRules">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 弹框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 编辑用户主体区域 -->
      <el-form :model="editForm" ref="editFormRef" label-width="70px" :rules="editFormRules">
        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setDialogClosed"
    >
      <div class="setrole">
        <p>当前用户名: {{userInfo.username}}</p>
        <p>当前角色: {{userInfo.role_name}}</p>
        <p>
          分配角色:
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) return callback()
      callback(new Error('请输入合法邮箱'))
    }
    // 验证手机号码
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) return callback()
      callback(new Error('请输入合法手机号码'))
    }
    return {
      // 获取用户列表的参数
      queryInfo: {
        query: '',
        pagenum: 1, // 当前的页数
        pagesize: 5 // 当天每页显示多少条数据
      },

      // 用户列表数据
      userlist: [],

      // 用户总条数
      total: '',

      // 隐藏显示用户对话框
      addDialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则
      addFormRules: {
        // 验证用户名
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        // 验证密码
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        // 验证邮箱
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 验证密码
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      // 显示隐藏编辑用户
      editDialogVisible: false,
      // 编辑用户的数据
      editForm: {},
      // 编辑用户表单验证规则
      editFormRules: {
        // 验证邮箱
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 验证密码
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      // 显示隐藏分配角色对话框
      setRoleDialogVisible: false,
      // 角色分配数据
      rolesList: [],
      // 当前用户和角色数据
      userInfo: {},
      // 当前分配角色的id
      selectRoleId: ''
    }
  },
  created() {
    // 获取用户列表数据
    this.geteUserList()
  },
  methods: {
    // 修改用户列表的状态值传递到后台
    async userStatueChange(userInfo) {
      const { data: res } = await this.$http.put(`/users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },

    // 监听pagesize的改变
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.geteUserList()
    },

    // 监听页码值的改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.geteUserList()
    },

    // 获取用户列表数据,渲染到页面
    async geteUserList() {
      const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.console.error(res.meta.msg)
      this.userlist = res.data.users
      this.total = res.data.total
      // console.log(res)
    },

    // 监听添加用户对话框的关闭事件,来实现重置表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.geteUserList()
      })
    },

    // 编辑用户
    async editUserHandle(id) {
      // 根据id发送请求
      const { data: res } = await this.$http.get(`users/${id}`)
      // 获取到要修改用户的数据
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听编辑用户对话框的关闭事件,重置编辑弹框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 实现编辑功能
    editUserInfo() {
      // 编辑前校验整个表单
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`/users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 更新成功之后的提示
        this.$message.success(res.meta.msg)
        // 刷新页面
        this.geteUserList()
        // 隐藏更新弹框
        this.editDialogVisible = false
      })
    },

    // 删除用户
    async removeUserById(id) {
      // $confirm返回的是一个promise对象
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定', // 点击确认者返回的值是一个字符串confirm,同意删除
        cancelButtonText: '取消', // 点击取消者返回的值是一个字符串cancel,取消删除
        type: 'warning'
      }).catch(err => err) // catch是捕获异常错误,列如取消,里面的err类似于 {return err}
      if (confirmResult !== 'confirm') {
        return this.$message.error('取消了删除')
      }
      // 执行删除操作
      const { data: res } = await this.$http.delete(`/users/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.geteUserList()
    },

    // 获取角色数据显示角色分配对话框
    async setRoles(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 实现分配角色功能
    async saveRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoleId })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.geteUserList()
      this.setRoleDialogVisible = false
    },
    // 重置分配角色对话框
    setDialogClosed() {
      this.selectRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
.setrole p {
  margin: 20px 0 0 20px;
}
</style>
